<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
    <el-form-item label="模板名称" prop="name">
      <el-input v-model="dataForm.name" placeholder="模板名称"></el-input>
    </el-form-item>
    <el-form-item label="模板类型" prop="type">
      <el-select v-model="dataForm.type" clearable placeholder="请选择" @change="showUpload">
        <el-option
          v-for="item in typeList"
          :key="item.code"
          :label="item.name"
          :value="item.code">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="上传excel模板" v-if="isShowUpload">
      <el-upload
        class="upload-demo"
        ref="upload"
        :action="actionUrl"
        :on-remove="handleRemove"
        :on-preview="handlePreview"
        :onError="uploadError"
        :onSuccess="uploadSuccess"
        :beforeUpload="beforeAvatarUpload"
        :file-list="fileList"
        :auto-upload="false"
        :headers="{token: this.$cookie.get('token')}">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        <div slot="tip" class="el-upload__tip">只能上传xlsx文件，大小不能超过10MB</div>
      </el-upload>
      <a class='download' v-if="isShowDownload" :href='downloadhttp' download=""  title="下载">下载</a>
    </el-form-item>
    
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import global_ from '@/components/tool/Global'

  export default {
    data () {
      return {
        visible: false,
        isShowUpload: false,
        isShowDownload: false,
        downloadhttp: '',
        serverFileUrl: global_.SERVER_FILE_URL,
        actionUrl: global_.SERVER_FILE_URL + "/frt/file/fileUpload",
        typeList: [],
        fileList: [],
        dataForm: {
          tempId: 0,
          name: '',
          type: '',
          url: '',
          createTime: ''
        },
        dataRule: {
          name: [
            { required: true, message: '模板名称不能为空', trigger: 'blur' }
          ],
          type: [
            { required: true, message: '模板类型不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      init (id) {
        this.dataForm.tempId = id || 0
        this.visible = true
        this.fileList = []
        this.isShowUpload = false
        this.isShowDownload = false
        
        this.$http({
          url: this.$http.adornUrl('/frt/template/select'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          this.typeList = data.list
        }).then(() => {
          this.visible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].resetFields()
          })
        }).then(() => {
          if (this.dataForm.tempId) {
            this.$http({
              url: this.$http.adornUrl(`/frt/template/info/${this.dataForm.tempId}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.name = data.template.name
                this.dataForm.type = data.template.type
                if(data.template.type == 'forestry_monitor'){
                  this.isShowUpload = true;
                  this.isShowDownload = true;
                  //TODO:上传路径127.0.0.1  
                  this.downloadhttp = this.serverFileUrl + '/frt/file/fileDownload?fileId='+data.template.fileId+'&token='+this.$cookie.get('token')
                }
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if(this.dataForm.type == 'forestry_monitor' && this.fileList.length == 0){
              this.$message.error('请先上传excel模板！')
              return false;
            }

            this.$http({
              url: this.$http.adornUrl(`/frt/template/${!this.dataForm.tempId ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'tempId': this.dataForm.tempId || undefined,
                'name': this.dataForm.name,
                'type': this.dataForm.type,
                'url': this.fileList.length > 0 ? this.fileList[0].url : '',
                'fileId': this.fileList.length > 0 ? this.fileList[0].fileId : ''
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      submitUpload() {
        this.$refs.upload.submit();
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {

        console.log(file);
      },
      // 上传成功后的回调
      uploadSuccess (response, file, fileList) {
        this.$message({
          message: response.msg,
          type: 'success',
          duration: 1500,
          onClose: () => {
          }
        });
        this.isShowDownload = true;
        //TODO:上传路径47.99.151.120
        this.downloadhttp = this.serverFileUrl + '/frt/file/fileDownload?fileId='+response.fileId+'&token='+this.$cookie.get('token')
        this.fileList = [{name: response.name, url: response.url, fileId: response.fileId}]
      },
      // 上传错误
      uploadError (response, file, fileList) {
        this.isShowDownload = false;
        this.$message.error('上传失败，请重试！')
      },
      // 上传前对文件的大小的判断
      beforeAvatarUpload (file) {
        const extension2 = file.name.split('.')[1] === 'xlsx'
        const isLt2M = file.size / 1024 / 1024 < 10
        if (!extension2) {
          this.$message.
          this.$message.error('上传模板只能是xlsx格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传模板大小不能超过 10MB!')
        }
        return extension2 && isLt2M
      },
      showUpload(curVal){
        if(curVal == 'forestry_monitor'){
          this.isShowUpload = true;
        }else{
          this.isShowUpload = false;
        }
      }
    }
  }
</script>
